
from django.shortcuts import render,redirect, get_list_or_404
from django.contrib.auth.decorators import login_required
from django.http import Http404

from .models import Topic,Entry
from .forms import TopicForm,EntryForm

# Create your views here.

def index(request):
    '''学习笔记的主页'''
    # 将request传递给这个视图函数
    return render(request, 'learning_logs/index.html')

@login_required  #修饰器：限制访问：只允许已登录的用户请求页面；这里修改默认重定向页面：可在修饰器函数中修改，也可在settings.py中添加路径
def topics(request):
    '''显示所有主题'''
    topics = Topic.objects.filter(owner=request.user).order_by('date_added') 
    # 搜索Topic对象，并根据日期排序
    topics = Topic.objects.order_by('date_added')
    # 使用字典context保存id下对应的条目内容
    context = {'topics': topics}
    # 返回context到topics.html模板中
    return render(request, 'learning_logs/topics.html', context)

@login_required
def topic(request, topic_id):
    '''显示单个主题及其所有条目'''
    topic = get_list_or_404(Topic, id=topic_id)
    
    # 确认请求的主题属于当前用户
    if topic.owner != request.user:
        raise Http404

    entries = topic.entry_set.order_by('-date_added')
    context = {'topic':topic, 'entries':entries}
    return render(request, 'learning_logs/topic.html', context)

@login_required
def new_topic(request):
    '''添加新主题'''

    if request.method != 'POST':
        # 未提交数据，创建一个新表单
        form = TopicForm()
    else:
        # POST提交的数据：对数据进行处理
        form = TopicForm(data=request.POST)
        # 新主题关联到当前登入的用户
        if form.is_valid():
            new_topic = form.save(commit=False)
            new_topic.owner = request.user  # 将新主题的owner属性设置为当前用户
            new_topic.save()  # 保存数据
            return redirect("learning_logs:topics")
    # 显示空表或指出表单数据无效
    context = {'form':form}
    return render(request,'learning_logs/new_topic.html',context)


@login_required
def new_entry(request,topic_id):
    '''特定主题中添加新条目'''

    topic = Topic.objects.get(id=topic_id)

    if request.method != 'POST':
        # 未提交数据：创建一个空表单
        form = EntryForm()
    else:
        # POST提交的数据：对数据进行处理
        form = EntryForm(data=request.POST)
        if form.is_valid():
            new_entry = form.save(commit=False)
            new_entry.topic = topic
            new_entry.save()
            return redirect('learning_logs:topic',topic_id=topic_id)

    # 显示空表单或指出表单数据无效
    context = {'topic':topic,'form':form}
    return render(request,'learning_logs/new_entry.html',context)

@login_required
def edit_entry(request, entry_id):
    ''''编辑既有条目'''
    entry = Entry.objects.get(id=entry_id)
    topic = entry.topic
    '''禁止用户输入URL来访问其他用户的条目:
        首先获取指定的条目以及与之相关联的主题，再检查主题所有者是否是当前登入的用户。
        不是则引发Http 404异常'''
    if topic.owner != request.user:
        raise Http404

    if request.method != 'POST':
        # 初次请求：使用当前条目填充表单
        form = EntryForm(instance=entry)
    else:
        # POST提交的数据：对数据进行处理
        form = EntryForm(instance=entry, data=request.POST)
        if form.is_valid:
            form.save()
            return redirect('learning_logs:topic',topic_id=topic.id)
    
    context = {'entry':entry,'topic':topic,'form':form}
    return render(request,'learning_logs/edit_entry.html',context)